<?php
namespace app\admin\service;

use app\common\model\ImageModel;
use app\common\model\MachineModel;
use app\common\model\ProtectModel;
use app\common\model\ReportModel;
use app\common\model\StationModel;
use app\common\model\TemplateModel;
use app\common\model\UserModel;
use app\common\model\OrderModel;

class OrderService
{
    private static $model;
    private static $stationModel;
    private static $userModel;
    private static $templateModel;
    private static $protectModel;
    private static $reportModel;
    private static $machineModel;
    private static $imageModel;

    public function __construct(OrderModel $orderModel,
                                ProtectModel $protectModel,
                                StationModel $stationModel,
                                UserModel $userModel,
                                TemplateModel $templateModel,
                                MachineModel $machineModel,
                                ImageModel $imageModel,
                                ReportModel $reportModel)
    {
        self::$model         = $orderModel;
        self::$stationModel  = $stationModel;
        self::$userModel     = $userModel;
        self::$templateModel = $templateModel;
        self::$protectModel  = $protectModel;
        self::$reportModel  = $reportModel;
        self::$machineModel  = $machineModel;
        self::$imageModel  = $imageModel;
    }

    /**
     *
     * User: zhouyao
     * Date: 2018/12/1
     * Time: 6:15 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['limit']) || !isset($params['page'])) {
            return app_fail(9997);
        }

        $condition = [];
        if ( !empty($params['status'])) {
            $condition['status'] = $params['status'] - 1;
        }

        if (!empty($params['order_name'])) {
            $condition['order_name'] = $params['order_name'];
        }

        $manager = self::$userModel->where(['id'=>$params['guid']])->find();
        $count = self::$model->where($condition)->count();
        if ($count < 1) {
            return ['data' => [], 'count' => (int) $count];
        }
        $result     = self::$model->where($condition)->page($params['page'], $params['limit'])->select();
        $result_arr = $result->toArray();
        $resCodeArr = array_column($result_arr, 'res_code');
        $userArr = array_column($result_arr, 'user_id');
        $stationArr = array_column($result_arr, 'station_id');
        $orderIdArr = array_column($result_arr, 'id');

        $report = self::$reportModel->whereIn('order_id', $orderIdArr)->column('machine_code, report_name, id', 'order_id');
        $machineCodeArr = array_column($report, 'machine_code');
        $reportIdArr = array_column($report, 'id');
        $machine = self::$machineModel->whereIn('machine_code', $machineCodeArr)->column('machine_name', 'machine_code');
        $image = $this->getReportImg($reportIdArr);
        $station = self::$stationModel->whereIn('id', $stationArr)->column('station_name', 'id');
        $user    = self::$userModel->whereIn('id', $userArr)->column('nickname', 'id');
        $protect    = self::$protectModel->whereIn('res_code', $resCodeArr)->column('res_name',
            'res_code');
        $result->each(function ($item) use ($station, $user, $protect, $manager, $report,
            $machine, $image) {
            $item->edit_limit = 0;//无编辑权限
            if($manager->type == 1 || $manager->id == $item->dispatch_user_id)
            {
                $item->edit_limit = 1;//有编辑权限
            }
            $item->res_name = isset($protect[$item->res_code]) ? $protect[$item->res_code] : '--';
            $item->station_name = isset($station[$item->station_id]) ? $station[$item->station_id] : '--';
            $item->nickname     = isset($user[$item->user_id]) ? $user[$item->user_id] : '--';
            $item->report_name     = isset($report[$item->id]) ? $report[$item->id]['report_name'] : '--';
            $item->machine_name     = (isset($report[$item->id]) && isset
                ($machine[$report[$item->id]['machine_code']])) ?
                $machine[$report[$item->id]['machine_code']] : '--';
            $item->images     = (isset($report[$item->id]) && isset
                ($image[$report[$item->id]['id']])) ?
                $image[$report[$item->id]['id']] : '--';
            $item->dispatch_date = $item->dispatch_date ? date('Y-m-d H:i:s', $item->dispatch_date) : '--';
            $item->accept_date = $item->accept_date ? date('Y-m-d H:i:s', $item->accept_date) : '--';
            $item->finish_date = $item->finish_date ? date('Y-m-d H:i:s', $item->finish_date) : '--';
            $item->dispatch_name = self::$userModel->where(['id' => $item->dispatch_user_id])->field('nickname')->find()['nickname'];
            $item->create_time = date('Y-m-d H:i:s', $item->create_time);

            $item->template_name = isset(self::$templateModel->where(['id' => $item->template_id])->column('template_name')[0]) ? self::$templateModel->where(['id' => $item->template_id])->column('template_name')[0] : '--';
            $item->status = intval($item->status);
            return $item;
        });

        return ['data' => $result, 'count' => (int) $count];
    }

    /**
     * zws
     * 添加工单
     * @param $params
     * @return bool|void
     */
    public function create($params)
    {
        if (empty($params) || !isset($params['user_id']) || !isset($params['res_code']) || !isset
            ($params['station_id']) || !isset
            ($params['template_id'])) {
            return app_fail(9983);
        }
        $data = array(
            'res_code'         => $params['res_code'],
            'station_id'       => $params['station_id'],
            'template_id'      => $params['template_id'],
            'user_id'          => $params['user_id'],
            'dispatch_user_id' => $params['guid'],
            'remark'           => isset($params['remark']) ? $params['remark'] : '',
            'status'           => 0,
            'dispatch_date'    => time(),
            'create_time'      => time(),
            'update_time'      => time(),
            'order_name'       => $params['order_name'],
        );
        try {
            $row = self::$model->allowField(true)->save($data);
            return $row;
        } catch (\Exception $e) {
            return app_fail(9998);
        }
    }
    public function getReportImg($report_ids)
    {
        if(empty($report_ids) || !is_array($report_ids))
        {
            return [];
        }
        $where = [['report_id', 'in', $report_ids]];
        $datas = [];
        $result = self::$imageModel->where($where)->select();
        $path = config('param_config.imagePath');
        $filePath = config('app.app_host').substr($path, 1);
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['report_id']][] = $v['img_url'] ? $filePath.$v['img_url'] : '';
            }
        }
        return $datas;
    }


    /**
     * zws
     * 查看当前工单
     * @param $param
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function edit($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail(9997);
        }

        // 查询当前工单
        $admin = self::$model->where('id', '=', $param['id'])
            ->find();

        return $admin;
    }

    /**
     * zws
     * 修改
     * @param $param
     * @return bool|void
     */
    public function update($param)
    {
        if (empty($param) || !isset($param['id'])) {
            app_fail( 9997);
        }
        $order_data = self::$model->where(['id'=>$param['id']])->find();
        if(!$order_data)
        {
            app_fail(6999);
        }
        if($order_data['status'] != 0)
        {
            app_fail(6998);
        }
        $user = self::$userModel->where('id', '=', $param['guid'])->find();
        if($user->type != 1 && $param['guid'] != $order_data['dispatch_user_id'])
        {
            app_fail(9984);
        }

        $data = [];
        // 拼装数据
        if (!isset($param['res_code']) && !empty($param['res_code'])) {
            $data['res_code'] = $param['res_code'];
        }
        if (!isset($param['user_id']) && !empty($param['user_id'])) {
            $data['user_id'] = $param['user_id'];
        }
        if (!isset($param['station_id']) && !empty($param['station_id'])) {
            $data['station_id'] = $param['station_id'];
        }
        if (!isset($param['template_id']) && !empty($param['template_id'])) {
            $data['template_id'] = md5($param['template_id']);
        }
//        $data['dispatch_date'] = $param['dispatch_date'];
        $data['update_time'] = time();
        if (!isset($param['remark']) && !empty($param['remark'])) {
            $data['remark'] = $param['remark'];
        }

        try {
            $admin = self::$model->save($data, ['id' => $param['id']]);
            return $admin;
        } catch (\Exception $e) {
            return app_fail(9899);
        }
    }

    /**
     * zws
     * 删除工单
     * @param $params
     * @return bool|void
     */
    public function delete($params)
    {
        if (empty($params) || !isset($params['guid']) || !isset($params['id'])) {
            return app_fail(9997);
        }

        $user = self::$userModel->where('id', '=', $params['guid'])->find();
        $row = self::$model->where('id', '=', $params['id'])->find();

        if ($user->type != 1 && $row['dispatch_user_id'] != $params['guid']) {
            return app_fail(1000);
        }
        if($row['status'] != 0 ){
            app_fail(6986);
        }
        try {
            self::$model->where('id', '=', $params['id'])->delete();
            return true;
        } catch (\Exception $e) {
            return app_fail(9980);
        }
    }

}